<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="110px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="供应商编号">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.supplier_num"
                placeholder="输入供应商编号"></el-input>
            </el-form-item>
            <el-form-item label="合作状态">
              <el-select filterable @change="onSearch(1)" class="form-width" v-model="formSearch.interact_status"
                placeholder="选择合作状态" clearable>
                <el-option label="合作中" :value="1">
                </el-option>
                <el-option label="已停止" :value="2">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供应产品大类">
              <el-select filterable @change="onSearch(1)" class="form-width" v-model="formSearch.product_type_id"
                placeholder="选择供应产品大类" clearable>
                <el-option :label="item.product_type_name" :value="item.Id" v-for="(item, index) in productTypeList"
                  :key="index">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="法人">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.corporation"
                placeholder="输入法人名称"></el-input>
            </el-form-item>
            <template v-if="moreSearchShow">
              <el-form-item label="法人联系电话">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.corporation_number"
                  placeholder="输入法人联系电话"></el-input>
              </el-form-item>
              <el-form-item label="联系人">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.contacts"
                  placeholder="输入联系人"></el-input>
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.contacts_number"
                  placeholder="输入联系电话"></el-input>
              </el-form-item>
              <el-form-item label="地址信息">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.contacts_address"
                  placeholder="输入地址信息"></el-input>
              </el-form-item>
              <el-form-item label="账户名称">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.account_name"
                  placeholder="输入账户名称"></el-input>
              </el-form-item>
              <el-form-item label="银行账号">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.account_number"
                  placeholder="输入银行账号"></el-input>
              </el-form-item>
              <el-form-item label="开户行">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.opening_bank"
                  placeholder="输入开户行"></el-input>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p>
          <el-button type="primary" @click="onSearch(1)">查询</el-button>
          <el-button type="primary" @click="addFunc" v-if="$isPer(permission, ['supplier_add'])">新增供应商</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList" v-loading="pageLoading">
      <div class="list-top-box">
        <p class="list-top-box-left">
          已选<span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }}数据
        </p>
        <div class="list-top-box-right">
          <el-button type="primary" :disabled="multipleSelection.length != 1" @click="editFunc"
            v-if="$isPer(permission, ['purchase_updateSupplier'])">编辑</el-button>
          <el-button type="danger" plain :disabled="multipleSelection.length == 0" @click="delFunc"
            v-if="$isPer(permission, ['purchase_deleteSupplier'])">删除</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="tableLoading">
        <el-table border ref="table" @row-click="handleHighlightChangeTable" highlight-selection-row :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData" v-loading="tableLoading"
          @selection-change="handleSelectionChange" height="100%">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column v-if="$fieldShowFunc('gys_gysbh')" min-width="150px" prop="supplier_num" label="供应商编号"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.supplier_num || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('gys_hzzt')" min-width="100px" prop="interact_status" label="合作状态"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.interact_status == 1 ? '合作中' : '停止合作' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('gys_gycpdl')" min-width="150px" prop="product_type_name" label="供应产品大类"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.product_type_name || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('gys_fr')" min-width="120px" prop="corporation" label="法人"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.corporation || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('gys_frlxdh')" min-width="130px" prop="corporation_number"
            label="法人联系电话" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.corporation_number || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('gys_lxr')" min-width="120px" prop="contacts" label="联系人"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.contacts || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('gys_lxdh')" min-width="130px" prop="contacts_number" label="联系电话"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.contacts_number || "--" }}
            </template>
          </el-table-column>t
          <el-table-column v-if="$fieldShowFunc('gys_dzxx')" min-width="180px" prop="contacts_address" label="地址信息"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.contacts_address || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('gys_zhmc')" min-width="180px" prop="account_name" label="账户名称"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.account_name || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('gys_yhzh')" min-width="180px" prop="account_number" label="银行账户"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.account_number || "--" }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('gys_khh')" min-width="180px" prop="opening_bank" label="开户行"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.opening_bank || "--" }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import commonApi from "@/api/common";
import { getUserInfo } from "@/utils/auth";
import purchaseApi from "@/api/purchaseApi";
export default {
  name: "supplierManagement",
  components: {},
  data() {
    return {
      tableLoading: false,
      userInfo: "",
      page: 1,
      tableData: [1],
      formSearch: {
        supplier_name: "",
        supplier_num: "",
        interact_status: "",
        product_type_id: "",
        corporation: "",
        corporation_number: "",
        contacts: "",
        contacts_number: "",
      },
      moreSearchShow: false,
      page: 1,
      num: 10,
      total: 0,
      addLoading: false,
      pageLoading: false,
      multipleSelection: [],
      productTypeList: [],//产品大类
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {},
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    // 操作权限
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.userInfo = getUserInfo();
    this.getSupplier();//供应商列表
    this.getProductType();//产品大类
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 页面权限
    getHtmlAuthority() {
      commonApi
        .getHtmlAuthority({
          path: this.$route.path,
        })
        .then((res) => {
          console.log(res, "页面权限");
          if (res.code == 200) {
            this.HtmlAuthority = res.data;
          }
        });
    },
    // 搜索
    onSearch(page) {
      page = typeof page == 'number' ? page : this.page;
      this.page = page;
      this.getSupplier();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    addFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: '/addSupplier',
        query: {
          route_title: '新增供应商'
        }
      })
    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    // ---------------------------供应商列表------------------------------------
    getSupplier() {
      let formSearch = this.formSearch;
      this.tableLoading = true;
      purchaseApi.getSupplier({
        page: this.page,
        num: this.num,
        supplier_name: formSearch.supplier_name || '',
        supplier_num: formSearch.supplier_num || '',
        interact_status: formSearch.interact_status || '',
        product_type_id: formSearch.product_type_id || '',
        corporation: formSearch.corporation || '',
        corporation_number: formSearch.corporation_number || '',
        contacts: formSearch.contacts || '',
        contacts_number: formSearch.contacts_number || '',
        contacts_address: formSearch.contacts_address || '',
        account_name: formSearch.account_name || '',
        account_number: formSearch.account_number || '',
        opening_bank: formSearch.opening_bank || ''
      }).then(res => {
        console.log(res, "供应商列表")
        this.tableLoading = false;
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      })
    },
    // ---------------------------编辑按钮------------------------------------
    editFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: '/addSupplier',
        query: {
          id: this.multipleSelection[0].Id,
          route_title: '编辑供应商'
        }
      })
    },
    // ---------------------------删除按钮------------------------------------
    delFunc() {
      let multipleSelection = this.multipleSelection;
      let arr = [];
      this.$confirm('此操作将永久删除已勾选供应商, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        multipleSelection.forEach(item => {
          arr.push(item.Id);
        })
        this.deleteSupplier(arr);
      }).catch(() => {
      });
    },
    // ---------------------------删除供应商------------------------------------
    deleteSupplier(delete_arr) {
      purchaseApi.deleteSupplier({ delete_arr }).then(res => {
        console.log(res, "删除供应商")
        if (res.code == 200) {
          this.onSearch();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // ----------------------------table点击行-选中----------------------------
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },
    // 产品大类
    getProductType() {
      purchaseApi.getProductType({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "产品大类")
        if (res.code == 200) {
          this.productTypeList = res.data.list;
        }
      })
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>